package com.example.aishop.controller;

import com.example.aishop.entity.Product;
import com.example.aishop.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/products")
public class ProductController {
    
    @Autowired
    private ProductService productService;
    
    // 创建产品
    @PostMapping
    public String createProduct(@RequestBody Product product) {
        boolean result = productService.save(product);
        if (result) {
            return "Product created successfully";
        } else {
            return "Failed to create product";
        }
    }
    
    // 根据ID查询产品
    @GetMapping("/{id}")
    public Product getProduct(@PathVariable Long id) {
        return productService.findById(id);
    }
    
    // 查询所有产品
    @GetMapping
    public List<Product> getAllProducts() {
        return productService.findAll();
    }
    
    // 更新产品
    @PutMapping("/{id}")
    public String updateProduct(@PathVariable Long id, @RequestBody Product product) {
        product.setId(id);
        boolean result = productService.update(product);
        if (result) {
            return "Product updated successfully";
        } else {
            return "Failed to update product";
        }
    }
    
    // 删除产品
    @DeleteMapping("/{id}")
    public String deleteProduct(@PathVariable Long id) {
        boolean result = productService.deleteById(id);
        if (result) {
            return "Product deleted successfully";
        } else {
            return "Failed to delete product";
        }
    }
}